package com.study.wanandroid.net

import android.content.Context
import com.study.wanandroid.entity.LoginResponseWrapper
import com.study.wanandroid.utils.LoadingDialog
import io.reactivex.Observer
import io.reactivex.disposables.Disposable


/**
 * <pre>
 *     author : slx
 *     time   : 2020/11/28
 *     desc   :
 * </pre>
 */
abstract class SimpleObserver<T>(val context: Context) : Observer<LoginResponseWrapper<T>> {

    // 是否弹出loading
    private var isShown: Boolean = true

    constructor(context: Context, isShow: Boolean = false) : this(context) {
        this.isShown = isShown
    }

    abstract fun onSuccess(data: T?)
    abstract fun onFailure(errorMsg: String?)

    override fun onSubscribe(d: Disposable) {
        if (isShown) {
            LoadingDialog.showLoading(context)
        }
    }

    override fun onComplete() {
        LoadingDialog.cancel()
    }

    override fun onError(e: Throwable) {
        onFailure("发生异常：${e.message}")
    }

    override fun onNext(t: LoginResponseWrapper<T>) {
        if (t?.data != null) {
            onSuccess(t.data)
        } else {
            onFailure("发生错误：${t.errorMsg}")
        }
    }
}